package com.rest.converter;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

/**
 * Created by HP on 2018/12/13.
 */

public class CommonInterceptor implements Interceptor {


    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();


        long t1 = System.nanoTime();
//        logger.info(String.format("Sending request %s on %s%n%s", request.url(),
//                chain.connection(), request.headers()));


        Response response = chain.proceed(request);
        JSONObject obj = null;
        Charset charset;
        charset = Charset.forName("UTF-8");
        ResponseBody responseBody = response.peekBody(Long.MAX_VALUE);
        Reader jsonReader = new InputStreamReader(responseBody.byteStream(), charset);
        BufferedReader reader = new BufferedReader(jsonReader);
        StringBuilder sbJson = new StringBuilder();
        String line = reader.readLine();
        do {
            sbJson.append(line);
            line = reader.readLine();
        } while (line != null);
        try {
            obj = new JSONObject(sbJson.toString());
            if (obj.optInt("code") != 200) {
                throw (new ApiException(obj.optInt("code"), obj.getString("message")));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

//        long t2 = System.nanoTime();
//logger.info(String.format("Received response for %s in %.1fms%n%s",
//                response.request().url(), (t2 - t1) / 1e6d, response.headers()));
        return response;
    }


}
